  
  
/*  
* Copyright @ 2017 com.iflysse.trains  
* xebest-erp 下午4:55:00  
* All right reserved.  
*  
*/  
  
package com.xebest.web.service.impl;  

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xebest.common.enums.erp.storehouse.VenStoreCheckResultEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreCheckStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreDeliveryTypeEnum;
import com.xebest.common.enums.erp.storehouse.VenStorePrintStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptStatusEnum;
import com.xebest.common.enums.erp.storehouse.VenStoreReceiptTypeEnum;
import com.xebest.util.BigDecimalUtil;
import com.xebest.util.seq.StoreHouseSeqUtil;
import com.xebest.web.form.XeVenStoreCheckForm;
import com.xebest.web.form.XeVenStoreListForm;
import com.xebest.web.form.XeVenStoreSaveCheckForm;
import com.xebest.web.mapper.read.XeVenStoreCheckDetailReadMapper;
import com.xebest.web.mapper.read.XeVenStoreCheckReadMapper;
import com.xebest.web.mapper.read.XeVenStoreInventoryDetailReadMapper;
import com.xebest.web.mapper.write.XeVenStoreCheckDetailWriteMapper;
import com.xebest.web.mapper.write.XeVenStoreCheckWriteMapper;
import com.xebest.web.model.XeVenStoreCheckDetailEntity;
import com.xebest.web.model.XeVenStoreCheckEntity;
import com.xebest.web.model.XeVenStoreDelivDetailEntity;
import com.xebest.web.model.XeVenStoreDeliveryEntity;
import com.xebest.web.model.XeVenStoreReceiptDetailEntity;
import com.xebest.web.model.XeVenStoreReceiptEntity;
import com.xebest.web.service.XeVenStoreCheckService;
import com.xebest.web.service.XeVenStoreDelivService;
import com.xebest.web.service.XeVenStoreReceiptService;
import com.xebest.web.view.ErpUserInfo;
import com.xebest.web.view.XeVenStoreCheckDetailView;
import com.xebest.web.view.XeVenStoreCheckView;



  
/**  
 * @desc: xebest-erp  
 * @author: 杜春静 
 * @createTime: 2017年6月24日 下午4:55:00  
 * @history:  
 * @version: v1.0    
 */
@Service
public class XeVenStoreCheckServiceImpl implements XeVenStoreCheckService {
	
	@Autowired
	XeVenStoreCheckReadMapper   xeVenStoreCheckReadMapper;//盘点单读
	@Autowired
	XeVenStoreCheckDetailReadMapper xeVenStoreCheckDetailReadMapper;//盘点单明细读
	@Autowired
	XeVenStoreCheckDetailWriteMapper xeVenStoreCheckDetailWriteMapper;//盘点单写
	@Autowired
	XeVenStoreCheckWriteMapper xeVenStoreCheckWriteMapper;//盘点单明细写
	@Autowired
	XeVenStoreReceiptService storeReceiptService;//入库单业务类
	@Autowired
	XeVenStoreDelivService storeDelivService;//出库单业务类
	@Autowired
	XeVenStoreInventoryDetailReadMapper invDetailMapper;//库存商品明细
	  
	@Override
	public List<XeVenStoreCheckView> listStoreCheckListByParam(
			Map<String, Object> param) {
		  
		return xeVenStoreCheckReadMapper.listStoreCheckByParam(param);  
		
	}
	
	/**
	 * 根据条件查询库存盘点单明细列表
	 */
	@Override
	public List<XeVenStoreCheckDetailView> listStoreCheckDetailByParam(
			XeVenStoreCheckForm form) {
		  
		return xeVenStoreCheckDetailReadMapper.listCheckDetailByParam(form);   
		
	}

	/**
	 * 添加库存盘点单 
	 * @throws Exception 
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int saveStoreCheck(XeVenStoreSaveCheckForm form,ErpUserInfo userInfo) throws Exception {
		int result = 0 ;
		String checkCode = StoreHouseSeqUtil.seqUtils.createCheckCode();
		XeVenStoreCheckEntity entity = new XeVenStoreCheckEntity();
		//转换盘点单数据
		String jsonString  = JSON.toJSONString(form, SerializerFeature.WriteMapNullValue,
                 SerializerFeature.WriteNullStringAsEmpty);
		entity = JSON.parseObject(jsonString,XeVenStoreCheckEntity.class);
		entity.setCheckCode(checkCode);
		entity.setUserCode(userInfo.getUserCode());
		entity.setCreateUser(userInfo.getLoginName());
		entity.setModifyUser(userInfo.getLoginName());
		//保存库存盘点单主表
		 result = xeVenStoreCheckWriteMapper.insertStoreCheck(entity);
		 List<XeVenStoreCheckDetailEntity> detailList = new ArrayList<XeVenStoreCheckDetailEntity>();
		 detailList = entity.getDetailList();
		 if(result>0){
			 if(detailList!= null && detailList.size()>0){
				 //保存库存盘点单从表
				result = xeVenStoreCheckDetailWriteMapper.batchInsertCheckDetail(detailList,checkCode,entity.getCreateUser());
			}
		 }
		
		return result;  
	}
	
	/**
	 * 添加库存盘点单  并完成盘点
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int saveFinishCheck(XeVenStoreSaveCheckForm form,ErpUserInfo userInfo) throws Exception {
		int result = 0 ;
		String checkCode = StoreHouseSeqUtil.seqUtils.createCheckCode();
		XeVenStoreCheckEntity entity = new XeVenStoreCheckEntity();
		//转换盘点单数据
		String jsonString  = JSON.toJSONString(form, SerializerFeature.WriteMapNullValue,
                 SerializerFeature.WriteNullStringAsEmpty);
		entity = JSON.parseObject(jsonString,XeVenStoreCheckEntity.class);
		entity.setUserCode(userInfo.getUserCode());
		entity.setCheckCode(checkCode);
		entity.setFinishDate(new Date());
		entity.setCreateUser(userInfo.getLoginName());
		entity.setModifyUser(userInfo.getLoginName());
		//保存库存盘点单主表
		 result = xeVenStoreCheckWriteMapper.insertStoreCheck(entity);
		 List<XeVenStoreCheckDetailEntity> detailList = new ArrayList<XeVenStoreCheckDetailEntity>();
		 detailList = entity.getDetailList();
		 if(result>0){
			 if(detailList!= null && detailList.size()>0){
				 //保存库存盘点单从表
				result = xeVenStoreCheckDetailWriteMapper.batchInsertCheckDetail(detailList,checkCode,entity.getCreateUser());
			}
		 }
		//进行出入库操作
		result =  this.finishCheckReceiptAndDeliv(entity,userInfo);
		return result;  
	}
	/*  
	 * 编辑时，完成盘点
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreCheckService#editFinishCheck(com.xebest.web.model.XeVenStoreCheckEntity)  
	*/  
	@Override
	@Transactional(value="writeTransactionManager")
	public int editFinishCheck(XeVenStoreCheckEntity entity,ErpUserInfo userInfo) throws Exception {
		int result = 0;
		//设置盘点单完成时间
		entity.setUserCode(userInfo.getUserCode());
		entity.setFinishDate(new Date());
		entity.setCreateUser(userInfo.getLoginName());
		entity.setModifyUser(userInfo.getLoginName());
		//更新盘点单主表信息
		result = xeVenStoreCheckWriteMapper.updateStoreCheckByEntity(entity);
		List<XeVenStoreCheckDetailEntity> detailList = entity.getDetailList();
		//更新盘点单从表信息
		if(result > 0){
			for(XeVenStoreCheckDetailEntity checkDetail : detailList){
				checkDetail.setCheckCode(entity.getCheckCode());
			}
			result = xeVenStoreCheckDetailWriteMapper.batchUpdateCheckDetail(entity.getDetailList());
			//获取修改后的盘点单主表的信息
			XeVenStoreCheckEntity checkEntity = xeVenStoreCheckWriteMapper.getStoreCheckById(entity.getCheckCode());
			checkEntity.setDetailList(detailList);
			//进行出入库操作
			result =  this.finishCheckReceiptAndDeliv(checkEntity,userInfo);
		}
		
	
		return result;  
		
	}
	/**
	 * 修改盘点单信息
	 * @author: 杜春静  
	 * @createTime: 2017年7月17日 下午4:21:07  
	 * @history:  
	 * @param entity
	 * @return
	 * @throws Exception int
	 */
	@Override
	@Transactional(value="writeTransactionManager")
	public int editStoreCheck(XeVenStoreCheckEntity entity) throws Exception {
		int result = 0;
		
		//更新盘点单主表信息
		result = xeVenStoreCheckWriteMapper.updateStoreCheckByEntity(entity);
		//更新盘点单从表信息
		if(result > 0){
			List<XeVenStoreCheckDetailEntity> detailList = entity.getDetailList();
			for(XeVenStoreCheckDetailEntity checkDetail : detailList){
				checkDetail.setCheckCode(entity.getCheckCode());
				checkDetail.setModifyUser(entity.getModifyUser());
			}
			result = xeVenStoreCheckDetailWriteMapper.batchUpdateCheckDetail( entity.getDetailList());
			
		}
		return result;  
		
	}
	/**
	 * 进行出入库操作
	 * @author: 杜春静  
	 * @createTime: 2017年7月17日 下午2:28:20  
	 * @history:  
	 * @param entity
	 * @return int
	 * @throws Exception 
	 */
	public int finishCheckReceiptAndDeliv(XeVenStoreCheckEntity entity,
			ErpUserInfo userInfo) throws Exception{
		int result = 0;
		List<XeVenStoreCheckDetailEntity> detailList = new ArrayList<XeVenStoreCheckDetailEntity>();
		detailList = entity.getDetailList();
	   //封装入库单
	   XeVenStoreReceiptEntity storeReceipt = new XeVenStoreReceiptEntity();
		storeReceipt.setStoreId(entity.getStoreId());
		storeReceipt.setStoreName(entity.getStoreName());
		storeReceipt.setUserCode(userInfo.getUserCode());
		storeReceipt.setRelationOrder(entity.getCheckCode());
		storeReceipt.setReceiptType(VenStoreReceiptTypeEnum.PY_RECEIPT.getValue());//入库类型为盘盈入库
		storeReceipt.setReceiptStatus(VenStoreReceiptStatusEnum.RECEIPT.getValue());//入库状态为已入库
		storeReceipt.setCreateUser(userInfo.getLoginName());
		storeReceipt.setModifyUser(userInfo.getLoginName());
		
		//封装出库主表信息
		XeVenStoreDeliveryEntity delivEntity = new XeVenStoreDeliveryEntity();
		delivEntity.setUserCode(userInfo.getUserCode());
		delivEntity.setRelationOrder(entity.getCheckCode());
		delivEntity.setStoreId(entity.getStoreId());
		delivEntity.setStoreName(entity.getStoreName());
		delivEntity.setDeliveryType(VenStoreDeliveryTypeEnum.INVENTORY_LOSS_DELIVERY.getValue());
		delivEntity.setDeliveryStatus(VenStoreDeliveryStatusEnum.DELIVERY.getValue());
		delivEntity.setPrintStatus(VenStorePrintStatusEnum.NO.getValue());
		delivEntity.setCreateUser(userInfo.getLoginName());
		delivEntity.setModifyUser(userInfo.getLoginName());
		//入库盘点单的状态为完成盘点
		 if(entity.getCheckStockStatus() == VenStoreCheckStatusEnum.FINISH.getValue()){
			//循环盘点单明细，封装入库从表信息
				List<XeVenStoreReceiptDetailEntity> receiptDetailList = new ArrayList<XeVenStoreReceiptDetailEntity>();
				//循环盘点单明细，封装出库从表信息
				List<XeVenStoreDelivDetailEntity> delivDetailList = new ArrayList<XeVenStoreDelivDetailEntity>();
				for(XeVenStoreCheckDetailEntity checkDetailEntity:detailList){
				 //盘盈入库
				 if(checkDetailEntity.getCheckStockResult().equals(VenStoreCheckResultEnum.INVENTORY_PROFIT.getValue())){
					//入库从表信息
						XeVenStoreReceiptDetailEntity receiptDetail = new XeVenStoreReceiptDetailEntity();
						receiptDetail.setProSku(checkDetailEntity.getProSku());
						//库存盘点成本价
						Map<String,Object> param = new HashMap<String, Object>();
						param.put("userCode", userInfo.getUserCode());
						param.put("storeId", entity.getStoreId());
						param.put("proSku", checkDetailEntity.getProSku());
						Map<String,Object> avgPriceMap= invDetailMapper.getInvProAvgPrice(param);
						BigDecimal avgPrice = new BigDecimal("0");
						if(null != avgPriceMap){
							if(null != avgPriceMap.get("avgPrice")){
								avgPrice = BigDecimalUtil.objectToBigDecimal(avgPriceMap.get("avgPrice"));
							}
						}
						receiptDetail.setBatchPrice(avgPrice);
						receiptDetail.setProNum(checkDetailEntity.getProNum());
						receiptDetail.setProCategoryId(checkDetailEntity.getProCategoryId());
						receiptDetail.setProCategoryName(checkDetailEntity.getProCategoryName());
						receiptDetail.setProName(checkDetailEntity.getProName());
						receiptDetail.setProUnit(checkDetailEntity.getProUnit());
						receiptDetail.setProSepcValue(checkDetailEntity.getProSpecValue());
						receiptDetail.setProPricingType(checkDetailEntity.getPricingType());
						receiptDetail.setCurrentInNum(checkDetailEntity.getCheckStockDifference());
						receiptDetail.setCreateUser(userInfo.getLoginName());
						receiptDetail.setModifyUser(userInfo.getLoginName());
						receiptDetailList.add(receiptDetail);
					//盘亏出库
				 } else if(checkDetailEntity.getCheckStockResult().equals(VenStoreCheckResultEnum.INVENTORY_LOSS.getValue())){//盘亏出库
					
							//出库从表信息
							XeVenStoreDelivDetailEntity delivDetail = new XeVenStoreDelivDetailEntity();
							delivDetail.setProSku(checkDetailEntity.getProSku());
							delivDetail.setProOutNum(checkDetailEntity.getCheckStockDifference());
							delivDetail.setProNum(checkDetailEntity.getProNum());
							delivDetail.setProCategoryId(checkDetailEntity.getProCategoryId());
							delivDetail.setProCategoryName(checkDetailEntity.getProCategoryName());
							delivDetail.setProName(checkDetailEntity.getProName());
							delivDetail.setProSpecValue(checkDetailEntity.getProSpecValue());
							delivDetail.setProPricingType(checkDetailEntity.getPricingType());
							//库存盘点成本价
							Map<String,Object> param = new HashMap<String, Object>();
							param.put("userCode", userInfo.getUserCode());
							param.put("storeId", entity.getStoreId());
							param.put("proSku", checkDetailEntity.getProSku());
							Map<String,Object> avgPriceMap= invDetailMapper.getInvProAvgPrice(param);
							BigDecimal avgPrice = new BigDecimal("0");
							if(null != avgPriceMap){
								if(null != avgPriceMap.get("avgPrice")){
									avgPrice = BigDecimalUtil.objectToBigDecimal(avgPriceMap.get("avgPrice"));
								}
							}
							delivDetail.setDelivBatchPrice(avgPrice);
							delivDetail.setProUnit(checkDetailEntity.getProUnit());
							delivDetail.setCreateUser(userInfo.getLoginName());
							delivDetail.setModifyUser(userInfo.getLoginName());
							delivDetailList.add(delivDetail);
				 }
			 }
			//进行入库操作	
				if(null != receiptDetailList && receiptDetailList.size() > 0){
					 storeReceipt.setReceiptDetailList(receiptDetailList);
					 result =storeReceiptService.saveStoreReceipt(storeReceipt);
				}
			
			 //进行出库操作
				if(null != delivDetailList && delivDetailList.size() > 0){
					 delivEntity.setDelivDtailList(delivDetailList);
					 result = storeDelivService.saveDeliv(delivEntity);
				}
			
		 }
		return result;
	}
	  
	/* 
	 * 批量废弃盘点单 
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreCheckService#batchDiscardCheck(com.xebest.web.form.XeVenStoreListForm, com.xebest.web.view.ErpUserInfo)  
	*/  
	@Override
	public int batchDiscardCheck(XeVenStoreListForm form,
			ErpUserInfo userInfo) throws Exception {
		int result = 0;
		String[] checkCodes = xeVenStoreCheckReadMapper.arrayCheckByParam(form.getCheckCodeS(), userInfo.getUserCode(), VenStoreCheckStatusEnum.CHECKING.getValue());
		if(null != checkCodes && checkCodes.length > 0){
			//批量更新盘点单为已废弃
			result = xeVenStoreCheckWriteMapper.batchUpdateCheckStatus(form.getCheckCodeS(), 
					VenStoreCheckStatusEnum.DISCARD.getValue(), userInfo.getUserCode(), userInfo.getLoginName());
		}
		return result;  
		
	}
	/*  
	 * 批量完成盘点
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreCheckService#batchFinishStockCheck(com.xebest.web.form.XeVenStoreListForm, com.xebest.web.view.ErpUserInfo)  
	*/  
	@Override
	@Transactional(value="writeTransactionManager")
	public int batchFinishStockCheck(XeVenStoreListForm form,
			ErpUserInfo userInfo) throws Exception {
		int result = 0;
		//要更新的盘点单号集合
		String userCode = userInfo.getUserCode();
		String[] checkCodes = xeVenStoreCheckReadMapper.arrayCheckByParam(form.getCheckCodeS(), userInfo.getUserCode(), VenStoreCheckStatusEnum.CHECKING.getValue());
		if(null != checkCodes && checkCodes.length > 0){
			//更新盘点单主表状态
			result = xeVenStoreCheckWriteMapper.batchUpdateCheckStatus(checkCodes,VenStoreCheckStatusEnum.FINISH.getValue(),
					userCode, userInfo.getLoginName());
			//查询要修改的盘点单列表
			List<XeVenStoreCheckEntity> checkList = this.xeVenStoreCheckReadMapper.listCheckByParam(checkCodes, userCode,VenStoreCheckStatusEnum.CHECKING.getValue());
			for(XeVenStoreCheckEntity checkEntity : checkList){
				checkEntity.setCheckStockStatus(VenStoreCheckStatusEnum.FINISH.getValue());
				List<XeVenStoreCheckDetailEntity> checkDetailList = xeVenStoreCheckDetailReadMapper.listCheckDetailByCheckCode(checkEntity.getCheckCode());
				checkEntity.setDetailList(checkDetailList);
				//进行出入库操作
				result =  this.finishCheckReceiptAndDeliv( checkEntity, userInfo);
			}
		}
		
		return result;  
	}
	
	
	  
	/*  
	 *(non-Javadoc)  
	 * @see com.xebest.web.service.XeVenStoreCheckService#getStoreCheckById(java.lang.String)  
	*/  
	
	@Override
	public XeVenStoreCheckEntity getStoreCheckById(String checkCode, boolean queryFlag) {
		XeVenStoreCheckEntity entity = new  XeVenStoreCheckEntity();
		entity = xeVenStoreCheckReadMapper.getStoreCheckById(checkCode);
		if(queryFlag){
			List<XeVenStoreCheckDetailEntity> checkDetailList = new ArrayList<XeVenStoreCheckDetailEntity>();
			checkDetailList = xeVenStoreCheckDetailReadMapper.listCheckDetailByCheckCode(checkCode);
			entity.setDetailList(checkDetailList);
		}
		
		return entity;  
	}

	  
	  
	
}
  
